﻿using System;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.SilverlightMediaFramework.Data;
using System.Collections.Generic;
using SMF.HowTo.Model;
using System.Xml.Linq;
using Microsoft.SilverlightMediaFramework;

namespace SMF.HowTo.Data
{
    public class VideoInfoDataClient : DataClient<IEnumerable<VideoInfo>>
    {
        public VideoInfoDataClient(Uri uri)
            : base(uri)
        {
            
        }

        protected override void OnRequestCompleted(object sender, SimpleEventArgs<string> e)
        {
            try
            {
                XDocument document = XDocument.Parse(e.Result);
                IEnumerable<VideoInfo> result = Map(document);
                OnFetchCompleted(result);
            }
            catch (Exception err)
            {
                OnFetchFailed(err);
            }
        }

        private static IEnumerable<VideoInfo> Map(XDocument document)
        {
            return document.Descendants("videoinfo")
                .Select(i => new VideoInfo
                {
                    Name = i.Attribute("name").GetValue(),
                    Description = i.Attribute("description").GetValue(),
                    Source = i.Attribute("sourceurl").GetValueAsUri(),
                    MarkersSource = i.Attribute("markersurl").GetValueAsUri()
                });
        }
    }
}
